package com.xiaoge.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.Jedis;

import java.net.UnknownHostException;

@Configuration
public class RedisConnnectionConfig {

    @Autowired
    StandaloneRedisConfig standaloneRedisConfig;

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Bean
    @ConditionalOnBean(value = {StandaloneRedisConfig.class})
    public RedisConnectionFactory standaloneRedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory(new RedisStandaloneConfiguration(standaloneRedisConfig.getHost(), standaloneRedisConfig.getPort()));
        return factory;
    }

    /**
     * 因为还没有看Redis支持的数据结构, 那么现在只是把Redis字符串模板类放到Spring 容器中, 后续再增加其他数据类型的支持
     * @return
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        return new StringRedisTemplate(redisConnectionFactory);
    }

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    public Jedis jedis(RedisConnectionFactory redisConnectionFactory){
        return new Jedis(standaloneRedisConfig.getHost(), standaloneRedisConfig.getPort());
    }
}
